<template>
  <div class="divSize" style="margin-top: 10%">
    <el-form
      ref="intvRuleFormRef"
      :model="intvInfo"
      status-icon
      :rules="intvRules"
      label-width="80px"
      label-position="right"
      :inline="true"
    >
      <h1 style="font-size: 26px; text-align: center">
        预约面试<el-button style="margin-left: 10px" type="danger" size="small" @click="Reset"
          >重置</el-button
        >
      </h1>
      <br />
      <div style="margin-left: 35%; margin-bottom: 20%">
        <h1 style="color: #909399">请选择你的面试时间:</h1>
        <br />
        <el-form-item prop="intvDate">
          <el-date-picker
            :disabled="intvDisabled"
            v-model="intvInfo.intvDate"
            placeholder="请选择"
            style="width: 350px"
            :disabled-date="intvDisabledDateFun"
          /> </el-form-item
        ><br />
        <el-form-item prop="intvTime">
          <el-select
            v-model="intvInfo.intvTime"
            placeholder="选择时间"
            :disabled="intvDisabled"
            style="width: 350px"
            clearable
            @visible-change="visibleChange"
          >
            <el-option
              v-for="item in timeList"
              :key="item.value"
              :label="item.value"
              :value="item.value"
              :disabled="item.disable"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <span style="font-size: 16px; color: #545c64">面试状态: &nbsp;&nbsp;</span>
          <span v-if="intvInfo.intvState === '未面试'" style="color: #e6a23c">{{
            intvInfo.intvState
          }}</span>
          <span v-if="intvInfo.intvState === '已面试'" style="color: #409eff">{{
            intvInfo.intvState
          }}</span>
          <span v-else-if="intvInfo.intvState === '未通过'" style="color: #f56c6c">{{
            intvInfo.intvState
          }}</span>
          <span v-else-if="intvInfo.intvState === '已通过'" style="color: #67c23a">{{
            intvInfo.intvState
          }}</span>

          <span v-if="intvInfo.intvState === '未通过' || intvInfo.intvState === '已通过'">
            <span style="font-size: 16px; color: #545c64; margin-left: 40px"
              >面试分数: &nbsp;&nbsp;</span
            >
            {{ intvInfo.intvScore }}
          </span> </el-form-item
        ><br />

        <el-form-item>
          <el-button type="warning" @click="cancer">{{ cancerButton }}</el-button>
          <span style="margin-left: 175px"></span>
          <el-button
            :disabled="intvDisabled"
            type="primary"
            @click="submitIntvForm(intvRuleFormRef)"
            >预约面试</el-button
          >
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { clearByIntvId, getIntvInfo, getIntvInfoByDate, saveIntvInfo } from '@/apis/bookInterview'
import { userStore } from '@/stores/user'
import { getInfo } from '@/apis/signup'
import { getTimeInfo } from '@/apis/time'
import Router from '@/router'
import { getExamInfo } from '@/apis/bookExam'

const userstore = userStore()
const intvRuleFormRef = ref<FormInstance>()
const intvDisabled = ref(true)
const cancerButton = ref('编辑预约')
const timeList = ref([{ value: '', disable: '' }])
const intvTime = ref({
  intvStartDate: '',
  intvEndDate: '',
  intvStartTime: '',
  intvEndTime: ''
})
const intvInfo = ref({
  intvId: '',
  intvDate: '',
  intvTime: '',
  intvState: '',
  intvScore: ''
})
const examInfo = ref({
  examId: '',
  examDate: '',
  examTime: '',
  examState: '',
  examScore: ''
})
const getStudentInfo = () => {
  getInfo(userstore.userInfo.studentId).then((res) => {
    console.log('获取学生信息')
    if (res.data.code === 1) {
      console.log('获取成功')
      userstore.userInfo = res.data.data
    } else {
      console.log('获取失败')
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
}

const getIntv = () => {
  if (userstore.userInfo.intvId != null && userstore.userInfo.intvId != '') {
    getIntvInfo(userstore.userInfo.intvId).then((res) => {
      console.log('获取预约面试信息')
      if (res.data.code === 1) {
        console.log('获取成功')
        intvInfo.value = res.data.data
        if (intvInfo.value === null) {
          intvInfo.value = {
            intvId: '',
            intvDate: '',
            intvTime: '',
            intvState: '',
            intvScore: ''
          }
        }
      } else {
        console.log('获取失败')
        ElMessage({ type: 'error', message: res.data.msg })
      }
    })
  }
}
const getExam = () => {
  if (userstore.userInfo.examId != null && userstore.userInfo.examId != '') {
    getExamInfo(userstore.userInfo.examId).then((res) => {
      console.log('获取预约考试信息')
      if (res.data.code === 1) {
        console.log('获取成功')
        examInfo.value = res.data.data
        if (examInfo.value != null) {
          if (examInfo.value.examState === '未考试' || examInfo.value.examState === '') {
            ElMessageBox.alert('未参加考试无法预约面试', '提示', {
              confirmButtonText: '确定',
              callback: () => {
                Router.replace('/index')
              }
            })
          } else if (examInfo.value.examState === '已考试') {
            ElMessageBox.alert('考试结果未确定无法预约面试', '提示', {
              confirmButtonText: '确定',
              callback: () => {
                Router.replace('/index')
              }
            })
          } else if (examInfo.value.examState === '未通过') {
            ElMessageBox.alert('很遗憾，您未通过考试，无法预约面试', '提示', {
              confirmButtonText: '确定',
              callback: () => {
                Router.replace('/index')
              }
            })
          } else if (intvInfo.value.intvState === '已通过') {
            ElMessageBox.alert('恭喜您通过面试，欢迎加入卓越班', '提示', {
              confirmButtonText: '确定',
              callback: () => {}
            })
          }
        }
      } else {
        console.log('获取失败')
        ElMessage({ type: 'error', message: res.data.msg })
      }
    })
  }
}
const getTime = () => {
  getTimeInfo().then((res) => {
    if (res.data.code === 1) {
      intvTime.value = res.data.data
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}
onMounted(() => {
  intvDisabled.value = true
  getIntv()
  getExam()
  getTime()
  userstore.defaultUrl = '/bookInterview'
})
const Reset = () => {
  if (
    Format(new Date()) > intvTime.value.intvStartDate &&
    Format(new Date()) < intvTime.value.intvEndDate
  ) {
    ElMessage({ type: 'error', message: '本次卓越班报名还未结束，无法重置' })
  } else {
    ElMessageBox.alert('重置后将从后台清除该面试所有信息，包括分数与状态，请谨慎', '危险', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      showCancelButton: true,
      type: 'warning'
    })
      .then(() => {
        clearByIntvId(intvInfo.value.intvId).then((res) => {
          if (res.data.code === 1) {
            ElMessage({ type: 'success', message: '操作成功' })
            getIntv()
          } else {
            ElMessage({ type: 'error', message: res.data.msg })
          }
        })
      })
      .catch(() => {})
  }
}
const intvRules = reactive<FormRules<typeof intvInfo>>({
  intvDate: [{ required: true, message: '请选择预约面试时间', trigger: 'blur' }],
  intvTime: [{ required: true, message: '请选择预约面试时间', trigger: 'blur' }]
})

const visibleChange = (visible: boolean) => {
  if (visible) {
    if (intvInfo.value.intvDate == '' || intvInfo.value.intvDate == null) {
      timeList.value = []
      return
    }
    let time = intvTime.value.intvStartTime
    let i = 0
    while (parseInt(time.split(':')[0]) <= parseInt(intvTime.value.intvEndTime.split(':')[0])) {
      timeList.value[i] = { value: time, disable: false }
      let h = parseInt(time.split(':')[0])
      let m = parseInt(time.split(':')[1])
      if (parseInt(time.split(':')[0]) == parseInt(intvTime.value.intvEndTime.split(':')[0])) {
        while (parseInt(time.split(':')[1]) < parseInt(intvTime.value.intvEndTime.split(':')[1])) {
          i++
          m += 10
          time = [h, m, '00'].join(':')
          timeList.value[i] = { value: time, disable: false }
        }
        timeDisable()
        return
      }
      if (m < 60) {
        m += 10
      }
      if (m == 60) {
        h += 1
        m = 0
      }
      if (h < 10) h = '0' + h
      if (m < 10) m = '0' + m
      time = [h, m, '00'].join(':')
      i++
    }
  }
}
const timeDisable = () => {
  if (intvInfo.value.intvDate != '' && intvInfo.value.intvDate != null) {
    if (typeof intvInfo.value.intvDate != 'string')
      intvInfo.value.intvDate = Format(intvInfo.value.intvDate)
    getIntvInfoByDate(intvInfo.value.intvDate).then((res) => {
      if (res.data.code === 1) {
        let intvList = res.data.data
        for (let i = 0; i < intvList.length; i++) {
          for (let j = 0; j < timeList.value.length; j++) {
            if (intvList[i].intvTime == timeList.value[j].value) {
              timeList.value[j].disable = true
            }
          }
        }
      } else {
        ElMessage({ type: 'error', message: res.data.msg })
      }
    })
  }
}

const cancer = () => {
  intvDisabled.value = intvDisabled.value === false
  if (cancerButton.value === '取消编辑') {
    if (intvInfo.value.intvId != null && intvInfo.value.intvId != '')
      getIntvInfo(intvInfo.value.intvId).then((res) => {
        intvInfo.value = res.data.data
      })
  }
  cancerButton.value = intvDisabled.value === false ? '取消编辑' : '编辑预约'
}

const submitIntvForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (typeof intvInfo.value.intvDate != 'string')
        intvInfo.value.intvDate = Format(intvInfo.value.intvDate)
      if (intvInfo.value.intvState != '未面试' && intvInfo.value.intvState != '') {
        ElMessage({ type: 'error', message: '面试已完成，无法再次预约面试' })
        return false
      } else if (Format(new Date()) >= intvTime.value.intvEndDate) {
        ElMessage({ type: 'error', message: '不在预约面试时间范围内' })
        return false
      } else {
        getIntvInfoByDate(intvInfo.value.intvDate).then((res) => {
          if (res.data.code === 1) {
            let intvList = res.data.data
            for (let i = 0; i < intvList.length; i++) {
              if (intvList[i].intvTime == intvInfo.value.intvTime) {
                ElMessage({ type: 'error', message: '该时间已有人预约，请重试' })
                return false
              }
            }
          } else {
            ElMessage({ type: 'error', message: res.data.msg })
          }
        })
      }
      intvInfo.value.intvState = '未面试'
      saveIntvInfo(intvInfo.value).then((res) => {
        if (res.data.code === 1) {
          intvInfo.value = res.data.data
          intvDisabled.value = true
          cancerButton.value = '编辑预约'
          ElMessage({ type: 'success', message: '预约成功' })
          console.log('保存成功')
          getStudentInfo()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
          console.log('保存失败')
        }
      })
    } else {
      console.log('error submit!')
      return false
    }
  })
}

function Format(date) {
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  if (month < 10) month = '0' + month
  if (day < 10) day = '0' + day
  return year + '-' + month + '-' + day
}
const intvDisabledDateFun = (date: Date) => {
  if (Format(date) >= intvTime.value.intvStartDate && Format(date) <= intvTime.value.intvEndDate)
    return false
  return true
}
</script>

<style>
.inputSize {
  width: 220px;
  height: 30px;
}
.divSize {
  margin: 15px;
}

.el-icon {
  margin-left: 8px;
  margin-right: 8px;
}
.demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-left: 8px;
  margin-right: 6px;
}
</style>
